// import 'dart:html';

import 'dart:convert';
import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hotwork/Myapplication.dart';
import 'package:flutter_hotwork/UploadDialog.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/bean/ListCheckProjectResultBean.dart';
import 'package:flutter_hotwork/homepage/BaseTitleBar.dart';
import 'package:flutter_hotwork/homepage/BaseViewBar.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:flutter_hotwork/utils/LogUtil.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';

import '../LoadingDialog.dart';
import '../Login.dart';
import '../Toast.dart';

// FlutterSound flutterSound = new FlutterSound();
class XunJianEditScreen extends StatefulWidget {
  @override
  XunJianEditState createState() => new XunJianEditState();
}

List<Widget> imageviews = new List();
ListCheckProjectResultBean listCheckProjectResultBean;
String imgs = "";
String videos = "";
String voices = "";
var voicesum = 0;
//用户类型的控制器
TextEditingController userController = TextEditingController();
VideoPlayerController videoPlayerController = VideoPlayerController.asset('');
ChewieController chewieController = ChewieController(
  videoPlayerController: videoPlayerController,
  aspectRatio: 1,
  autoPlay: true,
  looping: true,
);
final playerWidget = Chewie(
  controller: chewieController,
);

class XunJianEditState extends State<XunJianEditScreen> {
  //控制器
  TextEditingController inputController = TextEditingController();
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  bool imagesUpload = true;
  bool isuploadproblem = true;
  var _value;
  var index = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 初始化
    listCheckProjectResult();
    recordPlugin.initRecordMp3();
  }

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    recordPlugin.response.listen((data) {
      if (voicesum==0) {
        voicesum++;
        if (data.msg == "onStop") {
          ///结束录制时会返回录制文件的地址方便上传服务器
          print("onStop " + data.path);
          _upLoadImage(File(data.path), 2);
          LocalToast.toast(context, msg: "录音已结束");
        } else if (data.msg == "onStart") {
          print("onStart --");
          LocalToast.toast(context, msg: "录音已开始", showTime: 2000);
        }
      }
    });

    return Scaffold(
        appBar: new BaseViewBar(
            childView: new BaseTitleBar(
              "编辑",
              leftIcon: 'images/fanhui.png',
              rightIcon: "",
              rightClick: () {
                print("点击了右边干嘛啊。。。哦");
              },
              leftClick: () {
                Navigator.of(context).pop();
                print("点击了左边干嘛啊。。。哦");
              },
            ),
            preferredSize: Size.fromHeight(50.0)),
        body: new CustomScrollView(
          shrinkWrap: true,
          // 内容
          slivers: <Widget>[
            new SliverPadding(
              padding: const EdgeInsets.all(0),
              sliver: new SliverList(
                delegate: new SliverChildListDelegate(
                  <Widget>[
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        boxShadow: <BoxShadow>[
                          //设置阴影
                          new BoxShadow(
                            color: Colors.grey, //阴影颜色
                            // blurRadius:5.0,//阴影大小
                          ),
                        ],
                      ),
                      margin: EdgeInsets.all(10),
                      padding: EdgeInsets.all(10),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text("人员姓名:"),
                              Flexible(fit: FlexFit.tight, child: SizedBox()),
                              Text(MyApplication
                                  .loginuserinfo.userInfo.realname),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text("日期:"),
                              Flexible(fit: FlexFit.tight, child: SizedBox()),
                              Text(formatDate(new DateTime.now(), [
                                yyyy,
                                '-',
                                mm,
                                '-',
                                dd,
                                "  ",
                                HH,
                                ":",
                                nn,
                                ":",
                                ss
                              ])),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text("问题地点:"),
                              Flexible(fit: FlexFit.tight, child: SizedBox()),
                              Text(MyApplication.locationdetail != null
                                  ? MyApplication.locationdetail
                                  : ""),
                            ],
                          ),
                          null != listCheckProjectResultBean?.result &&
                                  listCheckProjectResultBean?.result.length > 0
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text("问题项目:"),
                                    Flexible(
                                        fit: FlexFit.tight, child: SizedBox()),
                                    DropdownButton(
                                        hint: Text('请选择问题项目'),
                                        value: _value,
                                        items: getListData(),
                                        onChanged: (value) {
                                          index = value;
                                          _value = value;
                                          setState(() {});
                                        })
                                  ],
                                )
                              : Container(),
                        ],
                      ),
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        boxShadow: <BoxShadow>[
                          //设置阴影
                          new BoxShadow(
                            color: Colors.grey, //阴影颜色
                            // blurRadius:5.0,//阴影大小
                          ),
                        ],
                      ),
                      margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                      padding: EdgeInsets.all(10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            child: Text("问题描述"),
                          ),

                          Container(
                            padding: const EdgeInsets.all(8.0),
                            margin: EdgeInsets.only(top: 10),
                            alignment: Alignment.center,
                            height: 100.0,
                            decoration: new BoxDecoration(
                                color: Colors.grey[300],
                                // border: new Border.all(color: Colors.black54, width: 2.0),
                                borderRadius: new BorderRadius.circular(5.0)),
                            child: new TextFormField(
                              maxLines: 5,
                              controller: userController,
                              style:
                                  TextStyle(fontSize: 12.0, color: Colors.grey),
                              //输入文本的样式
                              keyboardType: TextInputType.multiline,
                              decoration:
                                  InputDecoration.collapsed(hintText: '简要描述问题'),
                            ),
                          ),

                          Container(
                            padding: EdgeInsets.all(10),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                // Image(height:20,width: 20,image: AssetImage("images/shuaxin.png"),),
                                Text("照片文件"),
                              ],
                            ),
                          ),
                          Container(
                              height: _imagepaths.length > 0 ? 150 : 0,
                              child: GridView.builder(
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 3, //横轴三个子widget
                                          childAspectRatio: 1.0 //宽高比为1时，子widget
                                          ),
                                  itemCount: _imagepaths.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    return Image.file(_imagepaths[index]);
                                  })),
                          Row(
                            children: [
                              RaisedButton(
                                onPressed: _takePhoto,
                                child: Text('拍照'),
                              ),
                              RaisedButton(
                                onPressed: _openGallery,
                                child: Text("选择照片"),
                              ),
                            ],
                          ),
                          Container(
                            padding: EdgeInsets.all(10),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                // Image(height:20,width: 20,image: AssetImage("images/shuaxin.png"),),
                                Text("录音文件"),
                              ],
                            ),
                          ),
                          Row(
                            children: [
                              RaisedButton(
                                onPressed: () {
                                  recordPlugin.start();
                                },
                                child: Text('开始录音'),
                              ),
                              RaisedButton(
                                onPressed: () {
                                  recordPlugin.stop();
                                  voicesum = 0;
                                },
                                child: Text("结束录音"),
                              ),
                              RaisedButton(
                                onPressed: () {
                                  recordPlugin.play();
                                },
                                child: Text("回放录音"),
                              ),
                            ],
                          ),

                          Container(
                            padding: EdgeInsets.all(10),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                // Image(height:20,width: 20,image: AssetImage("images/shuaxin.png"),),
                                Text("视频文件"),
                              ],
                            ),
                          ),
                          Container(
                              height: _videopaths.length > 0 ? 350 : 0,
                              child: ListView.builder(
                                  itemCount: _videopaths.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    videoPlayerController =
                                        VideoPlayerController.file(
                                            _videopaths[index]);
                                    chewieController = ChewieController(
                                      videoPlayerController:
                                          videoPlayerController,
                                      aspectRatio: 1,
                                      autoPlay: true,
                                      looping: false,
                                    );
                                    return playerWidget;
                                  })),
                          Row(
                            children: [
                              RaisedButton(
                                onPressed: _takeVideo,
                                child: Text('录像'),
                              ),
                              RaisedButton(
                                onPressed: _getVideo,
                                child: Text("选择视频"),
                              ),
                            ],
                          ),

                          // Container(
                          //   child:
                          //   Text("整改意见"),
                          // ),

                          // Container(
                          //   padding: const EdgeInsets.all(8.0),
                          //   margin: EdgeInsets.only(top: 10,bottom: 10),
                          //   alignment: Alignment.center,
                          //   height: 100.0,
                          //   decoration: new BoxDecoration(
                          //       color: Colors.grey[300],
                          //       // border: new Border.all(color: Colors.black54, width: 2.0),
                          //       borderRadius: new BorderRadius.circular(5.0)),
                          //   child: new TextFormField(
                          //     maxLines: 5,
                          //     style: TextStyle(fontSize: 12.0, color: Colors.grey),//输入文本的样式
                          //     keyboardType: TextInputType.multiline,
                          //     decoration: InputDecoration.collapsed(hintText: '整改意见'),
                          //   ),
                          // ),

                          Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                InkWell(
                                  onTap: () {
                                      uploadproblem();
                                  },
                                  child: Container(
                                    width: 200,
                                    height: 30,
                                    decoration: BoxDecoration(
                                      color: Colors.blue,
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(15)),
                                      boxShadow: <BoxShadow>[
                                        //设置阴影
                                        new BoxShadow(
                                          color: Colors.blueGrey, //阴影颜色
                                          // blurRadius:5.0,//阴影大小
                                        ),
                                      ],
                                    ),
                                    child: Center(
                                      child: Text('上传',
                                          style: new TextStyle(
                                              color: Colors.white)),
                                    ),
                                  ),
                                ),
                              ]),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ));
  }

  @override
  void dispose() {
    _imagepaths = new List();
    _videopaths = new List();
    imgs = "";
    videos = "";
    voices = "";
    userController..text = "";
    listCheckProjectResultBean = null;
    videoPlayerController.pause();
    chewieController.pause();
    recordPlugin.dispose();
    super.dispose();
  }

  //上传图片
  _upLoadImage(File imagpath, int type) async {
    showDialog(
        context: context,
        builder: (context) {
          return new UploadDialog();
        });
    imagesUpload = false;
    String path = imagpath.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    // FormData formData = new FormData.fromMap({
    //   "file": new MultipartFile.fromFile (new File(path), name)
    // });
    try{
      if(type==1){
        String suffix = path.substring(path.lastIndexOf(".") + 1, path.length);
        if (Platform.isAndroid) {
          suffix = 'mp4';
        }
        int num = new DateTime.now().millisecondsSinceEpoch;
        name = num.toString() + '.' + suffix;
      }


      FormData formdata = FormData.fromMap(
          {"file": await MultipartFile.fromFile(path, filename: name)});
      var respone = await DioUtils.dio.post<String>(
          DioUtils.API_PREFIX + "/app/upload/upLoadFile",
          data: formdata);
      if (respone.statusCode == 200) {
        Map respMap = json.decode(respone.data);
        basebean base = basebean.fromJson(respMap);
        if (type == 0) {
          imgs += base.result.toString() + ",";
        } else if (type == 1) {
          videos += base.result.toString() + ",";
        } else {
          voices += base.result.toString() + ",";
        }
        LogUtil.d("数据" + imgs + "--------" + videos + "--------" + voices);
        imagesUpload = true;
      } else {
        _imagepaths.remove(imagpath);
        LogUtil.d("数据失败");
        imagesUpload = true;
        LocalToast.toast(context, msg: "文件过大，上传失败！");
      }
      Navigator.pop(context);
    }catch (e) {
      Navigator.pop(context);
      //  LocalToast.toast(context,msg: "网络错误");
      imagesUpload = true;
      print('请求出错：' + e.toString());
    }
  }

  //上传问题
  void uploadproblem() async {
    imgs.length;
    videos.length;
    voices.length;
    LogUtil.d("数据" + imgs + "--------" + videos + "--------" + voices);
    if (!imagesUpload) {
      LocalToast.toast(context, msg: "文件上传中。。。");
      return;
    }
    showDialog(
        context: context,
        builder: (context) {
          return new LoadingDialog();
        });
    var reqeuest = Map<Object, Object>();
    reqeuest["areaId"] = MyApplication.areaBean.areaId;
    reqeuest["areaName"] = MyApplication.areaBean.areaName;
    reqeuest["checkName"] = MyApplication.nowtaskbean.checkName;
    reqeuest["checkUser"] = MyApplication.loginuserinfo.userInfo.username;
    reqeuest["checkUserName"] = MyApplication.loginuserinfo.userInfo.realname;
    reqeuest["deviceId"] = MyApplication.areaDeviceBean["deviceId"];
    reqeuest["deviceName"] = MyApplication.areaDeviceBean["deviceName"];

    reqeuest["inspectorId"] = MyApplication.areaBean.inspectorId;
    reqeuest["projectId"] = MyApplication.areaDeviceBean2["projectId"];
    reqeuest["projectName"] = MyApplication.areaDeviceBean2["projectName"];
    if (null != MyApplication.projectBean.result &&
        MyApplication.projectBean.result.length > 0 &&
        index != -1) {
      reqeuest["projectResultId"] = MyApplication.projectBean.result[index].id;
      reqeuest["projectResultName"] =
          MyApplication.projectBean.result[index].projectResultName;
    }
    reqeuest["questionAddress"] = MyApplication.locationdetail;
    reqeuest["questionDescription"] = userController.text;
    reqeuest["questionType"] = "0";
    reqeuest["sitePhotosUrl"] = imgs;
    reqeuest["videoUrl"] = videos;
    reqeuest["voiceUrl"] = voices;
    reqeuest["lat"] = MyApplication.bd_decrypt().latitude;
    reqeuest["lon"] = MyApplication.bd_decrypt().longitude;
    reqeuest["userName"] = MyApplication.loginuserinfo.userInfo.username;
    reqeuest["checkId"] = MyApplication.nowtaskbean.id;
    reqeuest["createTime"] = formatDate(new DateTime.now(),
        [yyyy, '-', mm, '-', dd, "  ", HH, ":", nn, ":", ss]);
    try {
      Response response;
      response = await DioUtils.dio.post(
          DioUtils.API_PREFIX + "/checkQuestion/addQuestion",
          data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      Navigator.pop(context);
      if (base.code == 0) {
        LocalToast.toast(context, msg: "上报成功");
        Navigator.pop(context);
      } else if (base.code == 500) {
        LocalToast.toast(context, msg: "会话超时，请重新登陆！");
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new MyHomePage()),
          (route) => route == null,
        );
      }
      isuploadproblem=true;
      print('响应数据：' + response.toString());
    } catch (e) {
      Navigator.pop(context);
      isuploadproblem=true;
      print('请求出错：' + e.toString());
    }finally{
      isuploadproblem=true;
    }
  }

  void listCheckProjectResult() async {
    var areaDeviceBean =  MyApplication.areaDeviceBean2["projectId"];
    try {
      Response response;
      response = await DioUtils.dio.get(DioUtils.API_PREFIX +
          "/check/device/project/listCheckProjectResult?projectId=" +
          areaDeviceBean.toString());
      Map respMap = json.decode(response.data);
      listCheckProjectResultBean = ListCheckProjectResultBean.fromJson(respMap);
      setState(() {});
    } catch (e) {
      //  LocalToast.toast(context,msg: "网络错误");
      LogUtil.v('请求出错：' + e.toString());
    }
  }

  List<File> _imagepaths = new List();
  List<File> _videopaths = new List();

  /*拍照*/
  _takePhoto() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      if (null != image) {
        _imagepaths.add(image);
        _upLoadImage(image, 0);
        LogUtil.d("数据拍照" + image.path);
      }
    });
  }

  /*相册*/
  _openGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      if (null != image) {
        _imagepaths.add(image);
        _upLoadImage(image, 0);
        LogUtil.d("数据相册" + image.path);
      }
    });
  }

  /*选取视频*/
  _getVideo() async {
    var image = await ImagePicker.pickVideo(source: ImageSource.gallery);
    setState(() {
      if (null != image) {
        _videopaths.add(image);
        _upLoadImage(image, 1);
        LogUtil.d("数据相册视频" + image.path);
      }
    });
    print('选取视频：' + image.toString());
  }

/*拍摄视频*/
  _takeVideo() async {
    var image = await ImagePicker.pickVideo(
        source: ImageSource.camera, maxDuration: Duration(seconds: 10));
    setState(() {
      if (null != image) {
        _videopaths.add(image);
        _upLoadImage(image, 1);
        LogUtil.d("数据视频" + image.path);
      }
    });
    print('拍摄视频：' + image.toString());
  }

  List<DropdownMenuItem> getListData() {
    List<DropdownMenuItem> items = new List();
    for (int i = 0; i < listCheckProjectResultBean.result.length; i++) {
      items.add(DropdownMenuItem(
        child: Text(listCheckProjectResultBean.result[i].projectResultName),
        value: i,
      ));
    }
    return items;
  }

  /*luyin*/
  _takeSound() async {
    // file是文件名，比如Platform.isIOS ? 'ios.m4a' :
    // Future<String> result = (await flutterSound.startRecorder('android.mp4')) as Future<String>;
  }
}
